package me.zhengjie.modules.system.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.system.bo.*;
import okhttp3.*;

import java.io.*;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.net.URLEncoder;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cjl
 * @className BaiDuAiUtils
 * @description: TODO
 * @company: 上海明我信息技术有限公司
 * @date 2023年05月17日
 * @version: 1.0
 */
@Slf4j
public class BaiDuAiUtils {


        public static final String API_KEY = "Ney6CxOX7YIuqzmvtLQ9QztT";
        public static final String SECRET_KEY = "PCpIRVRCrYjqMvE89pmRTTSoSM9F9H9c";

        static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

        public static void main(String[] args) throws IOException {
            List<ResultV1Detail> ai = getAiV1("/Users/mingwork/Downloads/333.png");
            System.out.println(ai);
        }



    public static List<ResultV1Detail> getAiV1(String filePath)throws IOException{
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        // image 可以通过 getFileContentAsBase64("C:\fakepath\333.png") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(filePath,true)+"&baike_num=1");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String string = response.body().string();
        BaiDuV1Result jsonObject=JSONObject.parseObject(string, BaiDuV1Result.class);
        List<ResultV1Detail> collect = jsonObject.getResult().stream().sorted(Comparator.comparing(ResultV1Detail::getScore).reversed()).collect(Collectors.toList());
        System.out.println("baiduV1,"+JSON.toJSONString(jsonObject));
        System.out.println(collect.get(0).getScore());
        return collect;
    }

        public static List<Result> getAi(String filePath)throws IOException{
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            // image 可以通过 getFileContentAsBase64("C:\fakepath=1452296649,2265290831&fm=253&fmt=auto&app=138&f=JPEG.webp") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
            RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(filePath,true)+"&baike_num=1");
            Request request = new Request.Builder()
                    //植物识别  .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=" + getAccessToken())
                     .url("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String string = response.body().string();
            BaiDuResult jsonObject=JSONObject.parseObject(string, BaiDuResult.class);
            List<Result> collect = jsonObject.getResult().stream().sorted(Comparator.comparing(Result::getScore).reversed()).collect(Collectors.toList());
            System.out.println("baidu,"+JSON.toJSONString(jsonObject));
            System.out.println(collect.get(0).getScore());
            return collect;
        }

        /**
         * 获取文件base64编码
         *
         * @param path      文件路径
         * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
         * @return base64编码信息，不带文件头
         * @throws IOException IO异常
         */
        static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
            byte[] b = Files.readAllBytes(Paths.get(path));
            String base64 = Base64.getEncoder().encodeToString(b);
            if (urlEncode) {
                base64 = URLEncoder.encode(base64, "utf-8");
            }
            return base64;
        }


        /**
         * 从用户的AK，SK生成鉴权签名（Access Token）
         *
         * @return 鉴权签名（Access Token）
         * @throws IOException IO异常
         */
        static String getAccessToken() throws IOException {
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                    + "&client_secret=" + SECRET_KEY);
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            return jsonObject.getString("access_token");
        }

}
